import { readFileSync } from "fs";
const path = require('path');
import json from "@rollup/plugin-json";
import nodeResolve from "@rollup/plugin-node-resolve";
import { terser } from "rollup-plugin-terser";
import babel from "rollup-plugin-babel";
// 将 commonjs 的外部依赖打包为 ESModule 的形式引入
import commonjs from '@rollup/plugin-commonjs';
import postcss from 'rollup-plugin-postcss';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
const rollupPostcssLessLoader = require('rollup-plugin-postcss-webpack-alias-less-loader');
import meta from "./package.json";
// Extract copyrights from the LICENSE.
const copyright = readFileSync("./LICENSE", "utf-8")
  .split(/\n/g)
  .filter(line => /^Copyright\s+/.test(line))
  .map(line => line.replace(/^Copyright\s+/, ""))
  .join(", ");

const NODE_MODULE_PATH = path.resolve('./src');

const config = {
  input: "bundle.js",
  output: {
    file: `dist/${meta.name}.js`,
    name: meta.name,
    format: "umd",
    indent: false,
    extend: true,
    banner: `// ${meta.homepage} v${meta.version} Copyright ${copyright}`
  },
  plugins: [
    postcss({
      loaders: [
        // less 语法解析
        rollupPostcssLessLoader({
          nodeModulePath: NODE_MODULE_PATH,
          aliases: {},
        }),
      ],
      plugins: [
        // 自动追加前缀
        autoprefixer(),
        // css压缩
        cssnano()
      ],
      // extract: 'himg.css'
    }),
    nodeResolve({
      browser: true,
    }),
    json(),
    commonjs(),
    // babel解析
    babel({
      runtimeHelpers: true,
      exclude: ["node_modules/**","package.json"],
      externalHelpers: true
    })
  ],
  onwarn(message, warn) {
    if (message.code === "CIRCULAR_DEPENDENCY") return;
    // 忽略 eval提示
    if (/Use of eval is strongly discouraged/.test(message)) {
      return;
    }
    warn(message);
  }
};

export default [
  config,
  {
    ...config,
    output: {
      ...config.output,
      file: `dist/${meta.name}.min.js`
    },
    plugins: [
      ...config.plugins,
      terser({
        output: {
          preamble: config.output.banner
        },
        mangle: {
          reserved: [
            "InternMap",
            "InternSet"
          ]
        }
      })
    ]
  }
];
